var urls = { LOGIN_URL :"https://rmb.pingan.com.cn/brcp/uc/cust/uc-core.smart-login-new.do",
    Get_User_URL : "https://rmb.pingan.com.cn/brcp/uc/cust/uc-member.qryUserInfo.do",
    Get_Quotas_URL : "https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/queryLimitInfo",
    Query_Credit : "https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/queryCurrentBill",
    Query_Basic : "https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/slh/queryHistoryBillMonths",
    Done_Bills_Url : "https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/slh/getCurrentAndHistoryBill",
    Undone_Bills_Url : "https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/slh/queryFutureBill",
    Debit_body_url:"https://rmb.pingan.com.cn/brop/acct/cust/mgt/qryAccountBindList.do",
    Debit_Basic_url : "https://rmb.pingan.com.cn/brop/acct/cust/qry/qryBalanceController.do",
    Get_Interest_url : "https://rmb.pingan.com.cn/brop/acct/cust/qry/qryBalDetailController.do",
    Debit_Shopping_url : "https://rmb.pingan.com.cn/brop/acct/cust/qry/qryTranList.do",
    ImageCode_url:"https://rmb.pingan.com.cn/brcp/uc/cust/uc-core.get-validCode.do",
    Get_Full_Card_Num_URL:"https://capp.pingan.com.cn/paces_ccms_core/rest/pabank/creditcard/slh/pool/billMonthStageInit",
}
var  paramsCount = {
    USER_AGENT:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Mobile Safari/537.36",
    Public_Key : "BB955F6C6185B341C1A42EBF1FF9971B273878DBDAB252A0F1C305EBB529E116D807E0108BE6EDD47FF8DC5B6720FFE7F413CBB4ACDFB4C6BE609A5D60F5ADB261690A77755E058D4D9C0EC4FC2F5EB623DEBC88896003FBD8AFC4C3990828C66062A6D6CE509A2B0F8E06C4E332673FB86D235164B62B6110C1F1E0625B20ED"
}
var yyyy_MM_dd_PARSER = new SimpleDateFormat("yyyy-MM-dd");
var yyyyMMdd_PARSER = new SimpleDateFormat("yyyyMMdd");
var commMap = new HashMap();//公共信息
var month = "";
var debit_card_number = "";

var v4_pingan_mobile_credit_java_funcs = {
    openHomePage : function(){
        var indexHtml = luaFuncs.open("https://bank-static.pingan.com.cn/ibank/member/mobile/login/pages/login.html?__paramed__");
        storeDataToFile(context, indexHtml, "loginHtml.html")
        context.put("indexHtml01", indexHtml);
    },
    //检测代理是否可用方法
    checkProxyAvailable: function(){
        logger.info("任务【{}】,开始进行代理是否可用的检测",context.get(LUA_TASK_KEY));
        var indexHtml = context.get("indexHtml01");
        //判断是否代理异常的function
        var isCorrectFunc = function(indexHtml){
            var doc = Jsoup.parse(indexHtml);
            return (doc!=null && doc.select("#memberList")!=null);
        }
        //获取异常信息的方法function
        var getErrorMsgFunc = function(indexHtml) {
            return "代理ip异常";
        }
        //返回信息
        return assertTrueOrThrowException(indexHtml, isCorrectFunc, getErrorMsgFunc);
    },

    //检测网站控件是否可用--不需要
    checkControlAvailable:function () {
        logger.info("任务【{}】,平安银行网站控件是否可用检测",context.get(LUA_TASK_KEY));
        return true;
    },

    //检测网站是否可以正常访问 -- 不需要
    checkTargetWebsiteAvailable: function(){
        logger.info("任务【{}】, 进入检查平安银行网站是否可用方法", context.get(LUA_TASK_KEY));
        return true;
    },

    needResetEnvironment : function() {
        //return equals(context.get("currentErrorCode"), BALO_99602_50 || BALO_99602_40 || BALO_22006_10);
        return true;
    },
    needRefreshHomePageOrNot : function() {
        return true;
    },

    //登录流程
    login:function(){
        logger.info("任务【{}】,平安银行进入到登录流程",context.get(LUA_TASK_KEY));
        logger.info("----------------------------LOGIN START----------------------------")

        //----------------------------------------获取登录参数 判断登录方式是否正确--------------------------------------
        logger.info("任务【{}】,平安开始进行登录参数获取，登录方式的校验",context.get(LUA_TASK_KEY));
        var userName = getLoginParams(context)[0]; //用户名，可以是卡号，身份证号，手机号，自定义用户名
        var password = context.get(LUA_TASK_TOKEN); //账户密码
        //通过lua调用js方法对密码进行rsa加密
        password = luaFuncs.submitlogin(password,paramsCount.Public_Key);
        logger.info("任务【{}】,密码加密之后：{}",context.get(LUA_TASK_KEY),password);

        typeImageAndLogin();

        //-----------------------------------------开始进行登录----------------------------------------------------
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/ibank/member/mobile/login/pages/login.html?__paramed__");
        header.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36");
        var params = new HashMap();
        params.put("userId",userName);
        params.put("loginPwd",password);
        params.put("appId","KDH5_new_member");
        params.put("appVersion","1.0.0");
        params.put("channelId","CCMS");
        params.put("partnerId","null");
        params.put("mahId","");
        params.put("deviceName","broswer");
        params.put("deviceVersion","broswer");
        params.put("deviceId","KDH5_1536293210985601");
        params.put("encryptDeviceId","u1xDmdVBJiB5eYZXZGd+fyEfYQ/xIUfWW5O1OK1D9ek=");
        params.put("deviceType","web");
        params.put("osVerdion","1.0.0");
        params.put("pwdEncryptionType","0");
        params.put("cdata","");
        params.put("paFingerprint","");
        params.put("vcode",context.get("captchaResult"));
        params.put("responseDataType","JSON");
        //开始登录
        var loginhtml = post(urls.LOGIN_URL, params, header);
        //保存登录后的页面
        storeDataToFile(context, loginhtml, "login_result.txt");
        //获取登录错误信息
        var resultJson = JSON.parseObject(loginhtml);


        logger.info("任务【{}】，登录结束，返回登录结果信息：{}",context.get(LUA_TASK_KEY),loginhtml);
        //判断是否登录成功的流程
        var isLoginCorrectFunc = function(resultJson){
            return resultJson!=null && resultJson.get("responseCode") == "000000";
            //return false;
        }
        //获取登录异常信息的方法
        var getLoginErrorMsgFunc = function(resultJson) {
            if(resultJson.get("responseCode").equals("900101")){
                logger.info("任务【{}】，登录结束，返回900101",context.get(LUA_TASK_KEY));
                return "账号登录异常，请重新登录再进行操作";
            }else{
                return resultJson.get("responseMsg");
            }

            //return "账号登录异常，请重新登录再进行操作";
        }
        assertTrueOrThrowException(resultJson, isLoginCorrectFunc, getLoginErrorMsgFunc);
        logger.info("任务【{}】,平安银行登录成功，开始校验是否有卡片信息",context.get(LUA_TASK_KEY));

        //--------------------------------------------校验是否有卡片信息---------------------------------------------
        var isCard = checkIsCard();
        logger.info("任务【{}】,卡片信息校验完成，结果：{}",context.get(LUA_TASK_KEY),isCard);
        //校验是否有卡片的流程正确性
        var isCardCorrectFunc = function(isCard){
            return StringUtils.isNotBlank(isCard) && isCard.equals("true");
        }
        //获取卡片信息的错误码
        var getIsCardErrorMsgFunc = function(isCard) {
            return isCard;
        }
        logger.info("-----------------------------------------LGOIN END-----------------------------------------")
        assertTrueOrThrowException(isCard, isCardCorrectFunc, getIsCardErrorMsgFunc);
        //不需要图片验证码 短讯验证码
    },

    crawl:function(){
        //保存信用卡信息
        saveCreditInfo();
        //保存借记卡信息
        saveDebit();
        //判断上下文中是否有借记卡或者信用卡的信息，没有的话抛异常
        if(context.get("credit_data").isEmpty() && context.get("debit_data").isEmpty()){
            logger.info("平安银行未获取到卡片信息,taskKey:{}", context.get(LUA_TASK_KEY));
            throw new BankException(BALO_20304_30, "平安银行未获取到卡片信息");
        }
    },
    exitLogin:function () {
    },
    releaseResources:function(){}
}

function typeImageAndLogin(){
    var contentWillBeCheckedFunc = function(){
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/ibank/member/mobile/login/pages/login.html?__paramed__");
        header.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36");
        var params = new HashMap();
        params.put("deviceId","KDH5_1536295574326548");
        params.put("channelId","CCMS");
        params.put("deviceType","web");
        params.put("type","1");
        params.put("responseDataType","JSON");

        //开始登录
        var imageCode = post(urls.ImageCode_url, params, header);
        var image = JSON.parseObject(imageCode).get("image");
        var inage = JSON.parseObject(image).get("validImage");
        var code = inage.replaceAll("data:image/gif;base64,","");

        var Base64 = Java.type("java.util.Base64")
        var bytes = Base64.getDecoder().decode(code.replaceAll("\n", ""))

        var taskey = context.get(LUA_TASK_KEY);
        var year =taskey.substring(0,2);
        var mounth =taskey.substring(2,4);
        var date =taskey.substring(4,6);
        var imgPath = "D:\\htmlStorage\\BANK\\"+year+"\\"+mounth+"\\"+date+"\\"+taskey+"\\imageCode.gif";
        FileUtils.writeByteArrayToFile(new File(imgPath), bytes);

        context.put(TASK_IMG_PATH, imgPath);
        context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
        //var captchaResult = waitImgCodeBySecondsByJs(context,60,true,3);
        return waitImgCodeBySecondsByJs(context, 60, true, 3)

    }

    var isCorrectFunc = function(contentWillBeChecked){
        context.put("captchaResult",contentWillBeChecked);
        logger.info("{}",contentWillBeChecked);
        return contentWillBeChecked.length === 4
    }

    var getErrorMsgFunc = function(contentWillBeChecked){
        return "图片验证码错误"
    }

    repeaterAndAssertTrueOrThrowException(contentWillBeCheckedFunc, isCorrectFunc, getErrorMsgFunc, 3)


}

/**
 * 保存信用卡信息
 */
function saveCreditInfo(){
    //信用卡
    var dataList = new ArrayList();
    //存储对象
    var data = new CreditCardAllData();
    //保存基本信息
    var result = clickCreditCard(data);
    if(result != 0){
        //保存已出帐单
        saveDoneBills(data);
        //保存未出帐单
        saveUnDoneBills(data);
        dataList.add(data);
    }
    //将获取的信息存放到上下文中
    context.put("credit_data", dataList);
}


/**
 *
 * 保存借记卡信息
 */
function saveDebit(){
    var debitDataList = new ArrayList();
    //存储借记卡对象
    var debitData = new CreditCardAllData();
    //保存借记卡基本信息
    var data = saveDebitInfo(debitData);
    if(data != 0){
        //保存借记卡存款信息
        var debitresult = saveDebitDeposit(debitData);
        debitData.setFullCardNum(debit_card_number);
        if(debitresult != 0){
            //保存账单
            saveDebitBill(debitData);
            debitDataList.add(debitData);
        }
        //如果卡号不为空，重新设置借记卡卡号

    }

    //将抓取的数据存储到上下文中
    context.put("debit_data", debitDataList);
}


/**
 * 保存借记卡账单
 */
function saveDebitBill(debitData) {
    try{
        var billsList = debitData.getBills();
        var matter1 = new SimpleDateFormat("yyyy-MM-dd");
        var date = matter1.format(new Date());
        //获取现在的年份，借记卡可以抓取12个月的账单记录
        var currYear = Integer.parseInt(date.substring(0, 4));
        //一年前的年份
        var startYear = Integer.parseInt(currYear - 1);
        //开始查询账单的时间
        var startDate = new StringBuffer().append(startYear).append(date.substring(5, 8).replace("-", "")).toString();
        //开卡时间
        var openDate = new SimpleDateFormat("yyyy-MM").parse(context.get("openTime").substring(0, 8));
        var beginDate = new SimpleDateFormat("yyyyMM").parse(startDate);
        //如果开始查询时间在开卡时间之前
        if (beginDate.before(openDate)) {
            //开始查询日期就是开卡日期
            startDate = new StringBuffer().append(context.get("openTime").substring(0, 7).replace("-", "")).toString();
        }
        var count = 0;
        for (var i = 0; i <= 12; i++) {
            //开始查询时间
            var youngDate = new SimpleDateFormat("yyyyMMdd").parse(new StringBuffer().append(startDate).append(date.substring(8,10)).toString());
            //如果开始查询时间在当前时间之前
            if (youngDate.before(new Date())) {
                count++;
                //下个月的月份
                var NextDate = getLimitMes(startDate);
                var billAllData = new BillAllData();
                billAllData.setBillId(UUID.randomUUID().toString());//账单编号
                billAllData.setBillType("");//账单类型，借记卡为""
                billAllData.setBankName("平安银行");//银行
                //账单月份
                var billMonth = new StringBuffer().append(startDate.substring(0, 4)).append("-").append(startDate.substring(4, 6)).toString();
                billAllData.setBillMonth(billMonth);
                //账单日
                billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(new StringBuffer().append(billMonth).append("-").append("01").toString()));
                //将下次查询的开始月份存储到上下文中
                context.put("NextDate", new StringBuffer().append(NextDate).append("01").toString());
                var start;
                //计算开始日期
                if(count == 1){
                    start = new StringBuffer().append(startDate).append(date.substring(8,10)).toString();
                }else{
                    start = new StringBuffer().append(startDate).append("01").toString();
                }
                //保存借记卡消费记录
                saveDebitShopping(billAllData, start, count);
                //下次查询时的开始日期等于上文计算好的下个月的月份
                startDate = NextDate;
                billsList.add(billAllData);
            } else {
                break;
            }
        }
    } catch (e) {
        logger.error("taskKey={} 借记卡账单抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 保存借记卡消费记录
 */
function saveDebitShopping(billAllData,startDate,count){
    try{
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/brac-ia/accountBalance/pages/transactionDetail/transaction.html?bankCardSign="+context.get("bankCardSign"));
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("accNum",context.get("bankCardSign"));
        params.put("bankType","0");
        params.put("currType",context.get("preferCcy"));
        params.put("startDate",startDate);
        params.put("endDate",context.get("NextDate"));
        params.put("pageIndex","1");
        params.put("pageSize","10");
        //查询这一个月中的所以消费记录
        var ShoppingInfo = post(urls.Debit_Shopping_url, params, header);
        storeDataToFile(context,ShoppingInfo, "debit_shopping_info"+count+".txt");
        var shoppingMap = JSON.parseObject(ShoppingInfo);
        //判断官网是否异常即是否有消费记录
        if(ShoppingInfo.isEmpty() || ShoppingInfo.contains("网络繁忙") || shoppingMap.get("data")==null){
            return billAllData;
        }
        //判断是否有消费记录
        if(Integer.parseInt(shoppingMap.get("data").get("count")) == 0 || shoppingMap.get("data").get("result_value").isEmpty()){
            return billAllData;
        }
        //获取交易记录，是一个集合
        var debitShoppingList = shoppingMap.get("data").get("result_value");
        //保存借记卡消费记录
        setShoppingSheet(debitShoppingList,billAllData);
    } catch (e) {
        logger.error("taskKey={} 借记卡消费记录抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 借记卡消费信息
 */
function setShoppingSheet(debitShoppingList,billAllData){
    try {
        var count = 0;
        //循环次数为所有消费记录的条数
        for (var i = 0; i < debitShoppingList.size(); i++) {
            var expense = new Expense();
            count++;
            //卡号
            var fullCardNum = debitShoppingList.get(i).get("fromAcctNo");
            //卡号后四位
            var card_num = fullCardNum.substring(fullCardNum.length() - 4, fullCardNum.length());
            //判断借记卡的消费类型
            var category = checkShoppingType(debitShoppingList.get(i).get("remark"));
            //如果没有匹配的消费类型，则消费类型为其他
            if (category.isEmpty()) {
                category = "OTHERREVENUE";
            }
            //判断交易金额是正数还是负数，支出金额取正数；收入金额取负数
            if (debitShoppingList.get(i).get("tranFlag").contains("00")) {
                expense.setAmountMoney(new BigDecimal(debitShoppingList.get(i).get("tranAmt")));
            } else {
                expense.setAmountMoney(new BigDecimal(new StringBuffer().append("-").append(debitShoppingList.get(i).get("tranAmt") == null ? 0 : debitShoppingList.get(i).get("tranAmt")).toString()));
            }
            //消费记录编号
            expense.setId(UUID.randomUUID().toString());
            //卡号
            expense.setCardNum(card_num);
            //判断记账日期是否为空
            if (debitShoppingList.get(i).get("tranDate") == null) {
                expense.setPostDate("");
            } else {
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(debitShoppingList.get(i).get("tranDate")));
            }
            //消费类型
            expense.setCategory(category);
            //排序
            expense.setOrderIndex(count);
            //交易时间
            if (debitShoppingList.get(i).get("tranTime") == null) {
                expense.setTransDate("");
            } else {
                expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(debitShoppingList.get(i).get("tranTime")));
            }
            //币种
            expense.setCurrencyType(debitShoppingList.get(i).get("currType"));
            //账户余额
            expense.setBalance(new BigDecimal(debitShoppingList.get(i).get("balance")));
            //交易地点
            expense.setTransAddr(debitShoppingList.get(i).get("fromBankName"));
            //交易方式
            expense.setTransMethod("");
            //交易通道
            expense.setTransChannel("");
            //交易描述
            expense.setDescription(debitShoppingList.get(i).get("remark"));
            //备注
            expense.setRemark(debitShoppingList.get(i).get("remark"));
            //对方卡号
            expense.setOppositeCardNo(debitShoppingList.get(i).get("toAcctNo"));
            //对方持卡人
            expense.setNameOnOppositeCard(debitShoppingList.get(i).get("toClientName"));
            //对方银行
            expense.setOppositeBank(debitShoppingList.get(i).get("toBranchName"));
            billAllData.getShoppingSheets().add(expense);
        }
    } catch (e) {
        logger.error("taskKey={} 借记卡消费信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 借记卡的消费类型
 */
function checkShoppingType(description){
    if(description.contains("工资")){
        return "SALARY";
    }else if(description.contains("奖金")){
        return "BONUS";
    }else if(description.contains("利息")){
        return "ACCRUAL";
    }else if(description.contains("存现")){
        return "DEPOSIT";
    }else if(description.contains("转账")){
        return "TRANSFER";
    }else if(description.contains("借贷")){
        return "LOANS";
    }else if(description.contains("冲账")){
        return "REVERSE";
    }else if(description.contains("退款")){
        return "REFUND";
    }else if(description.contains("其它收入")){
        return "OTHERREVENUE";
    }else if(description.contains("收益")){
        return "EARNINGS";
    }else if(description.contains("报销")){
        return "CLAIM";
    }else if(description.contains("取现")){
        return "WITHDRAW";
    }else if(description.contains("手续费")){
        return "HANDLINGFEE";
    }else if(description.contains("理财")){
        return "FINANCE";
    }else if(description.contains("消费")){
        return "CONSUMPTION";
    }else if(description.contains("社保")){
        return "SOCIALSECURITY";
    }else if(description.contains("通讯费")){
        return "COMMUNICATIONFEE";
    }else if(description.contains("生活费")){
        return "LIVINGEXPENSE";
    }else if(description.contains("转账")){
        return "TRANSFER";
    }else if(description.contains("还贷")){
        return "REPAYMENT";
    }else if(description.contains("公积金")){
        return "FUND";
    }else if(description.contains("房租")){
        return "RENT";
    }else if(description.contains("其他费用")){
        return "OTHERFEE";
    }else if(description.contains("其它支出")){
        return "OTHEREXPENSE";
    }else{
        return "";
    }
}

/**
 * 保存借记卡存款信息
 */
function saveDebitDeposit(debitData){
    try{
        var depositsList = debitData.getDeposits();
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/brac-ia/accountBalance/pages/demandDepositDetail.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("bankCardSign",context.get("bankCardSign"));
        params.put("bussType",context.get("accountType"));
        params.put("ccy",context.get("preferCcy"));
        var InterestInfo = post(urls.Get_Interest_url, params, header);
        storeDataToFile(context,InterestInfo, "debit_interest_info.txt");


        //判断是否为空
        if(InterestInfo.isEmpty()){
            return 0;
        }
        //重试防止网络繁忙
        for(var i = 0;i<=3;i++){
            if(InterestInfo.contains("网络繁忙，请稍后重试")){
                InterestInfo = post(urls.Get_Interest_url, params, header);
                storeDataToFile(context,InterestInfo, "debit_interest_info"+i+".txt");
            }else{
                break;
            }
        }
        if(InterestInfo.contains("网络繁忙，请稍后重试")){
            return 0;
        }
        var interestMap = JSON.parseObject(InterestInfo);
        if(interestMap.get("data") == null){
            return 0;
        }

        debit_card_number = interestMap.get("data").get("accNum");
        //获取存款利率
        var interest = interestMap.get("data").get("interestRate");
        var creditDeposit =  new CreditCardTimeDeposit();
        //判断卡类型
        var cardType = checkCardType();
        //判断人民币类型
        // var moneyType = checkMoneyType();
        creditDeposit.setBalance(new BigDecimal(context.get("balance")));
        //卡类型
        creditDeposit.setDepositType(cardType);
        //存款币种
        creditDeposit.setCurrencyType(context.get("preferCcy"));
        //起息日期
        creditDeposit.setDepositDate(null);
        //到期日期
        creditDeposit.setDueDate(null);
        //存期
        creditDeposit.setPeriod(0);
        //存期单位
        creditDeposit.setPeriodUnit("");
        //存款利率
        creditDeposit.setInterest(new BigDecimal(interest));
        depositsList.add(creditDeposit);
    } catch (e) {
        logger.error("taskKey={} 借记卡存款信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 判断钱的类型
 */
function checkMoneyType(){
    var preferCcy = context.get("preferCcy");
    switch (preferCcy) {
        case "RMB":
        case "CNY":
            return "人民币";
        case "GBP":
            return "英镑";
        case "HKD":
            return "港币";
        case "USD":
            return "美元";
        case "CHF":
            return "瑞士法郎";
        case "SGD":
            return "新元";
        case "EUR":
            return "欧元";
        case "JPY":
            return "日元";
        case "CAD":
            return "加元";
        case "AUD":
            return "澳元";
        default:
            return "";
    }
}

/**
 * 判断卡类型
 */
function checkCardType(){
    var accountType = context.get("accountType");
    switch (accountType) {
        case "7101":
            return "智能日添利";
        case "8701":
            return "活期预付卡";
        case "8801":
            return "活期委托";
        case "8901":
            return "活期结构";
        case "8101":
        case "8102":
            return "活期";
        case "8103":
            return "活期资本";
        case "8104":
            return "日日生金";
        case "8301":
            return "活期支票";
        case "8601":
        case "8605":
        case "8606":
        case "8607":
        case "8608":
        case "8609":
        case "8610":
        case "8611":
            return "活期";
        case "9102":
            return "大额整整";
        case "9103":
            return "整整资本";
        case "9104":
            return "整整(存单)";
        case "9101":
            return "整整";
        case "9112":
            return "整整(助农卡)";
        case "9201":
            return "零整";
        case "9106":
            return "定活通";
        case "9202":
            return "聚存宝";
        case "9603":
            return "通知存款资本";
        case "9601":
            return "通知存款(助农卡)";
        case "9602":
            return "通知存款(存单)";
        case "8201":
            return "定活两便";
        case "8202":
            return "定活两便(存单)";
        case "9301":
            return "存本取息";
        case "9109":
            return "大额存单";
        case "9105":
        case "9108":
        case "9604":
            return "智能存款-人民币";
        default:
            return "活期";
    }
}

/**
 * 保存借记卡基本信息
 */
function saveDebitInfo(debitData){
    try{
        //获取卡片标记
        var bankCardSign = getbody();
        //判断是否与为空
        if(bankCardSign.isEmpty()){
            return 0;
        }
        //将卡片标记存储到上下文中
        context.put("bankCardSign",bankCardSign);
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/brac-ia/accountBalance/pages/demandDeposit.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("bankCardSign",bankCardSign);
        //请求借记卡的基本信息
        var debitBasicInfo = post(urls.Debit_Basic_url, params, header);
        storeDataToFile(context,debitBasicInfo, "debit_basic_info.txt");
        //判断卡片状态是否正常
        if(debitBasicInfo.isEmpty() ||  debitBasicInfo.contains("未完成身份认证") || debitBasicInfo.contains("需要您重新添加绑定卡后才能正常使用")){
            return 0;
        }
        var debitBasicMap = JSON.parseObject(debitBasicInfo);
        //判断借记卡基本信息是否为空
        if(debitBasicMap.get("data") == null || debitBasicMap.get("data").get("acctInfoList").isEmpty()){
            return 0;
        }
        var debitList = debitBasicMap.get("data").get("acctInfoList").get(0);
        var debitMap = JSON.parseObject(debitList);
        //卡号
        var full_card_num = debitMap.get("cardInfo").get("bankCardMask");
        //获取持卡人姓名
        var name_oncard = getName();
        var balance;
        //获取借记卡余额
        if(debitMap.get("hqBalanceDTOList").isEmpty()){
            balance = "0";
        }else{
            var hqBalanceDTOList = debitMap.get("hqBalanceDTOList").get(0);
            balance = JSON.parseObject(hqBalanceDTOList).get("rmbBalance");
            if(balance == null){
                balance = "0";
            }
        }
        context.put("balance",balance);
        //卡的编号
        debitData.setCardId(UUID.randomUUID().toString());
        //卡类型
        debitData.setCardType("借记卡");
        //银行
        debitData.setBankName("平安银行");
        //卡号
        debitData.setFullCardNum(full_card_num);
        //卡号后四位
        debitData.setCardNum(full_card_num.substring(full_card_num.length()-4,full_card_num.length()));
        //持卡人姓名
        debitData.setNameOnCard(name_oncard);
        //借记卡余额
        debitData.setBalance(new BigDecimal(balance));
        //可用取现额度
        debitData.setCashBalance(null);
        //现金额度
        debitData.setCashLimit(null);
        //信用额度
        debitData.setCreditLimit(null);
        //开户银行
        debitData.setOpenBank("平安银行");
        //判断是否为空
        if(debitMap.get("cardInfo")==null || debitMap.get("cardInfo").get("openDate") == null){
            var matter1 = new SimpleDateFormat("yyyy-MM-dd");
            var date = matter1.format(new Date());
            debitData.setOpenTime(yyyy_MM_dd_PARSER.parse(date));
            context.put("openTime",date);
        }else{
            //开卡时间
            var date = null;
            var strDate = debitMap.get("cardInfo").get("openDate").toString()
            if(strDate.length == 8){
                date = yyyyMMdd_PARSER.parse(strDate);
            }else{
                date = yyyy_MM_dd_PARSER.parse(strDate);
            }
            debitData.setOpenTime(date);
            context.put("openTime",debitMap.get("cardInfo").get("openDate"));
        }
        context.put("accountType",debitMap.get("cardInfo").get("accountType"));
        context.put("preferCcy",debitMap.get("cardInfo").get("preferCcy"));
    } catch (e) {
        logger.error("taskKey={} 借记卡基本信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 获取请求体
 *
 */
function getbody(){
    try{
        var header = new HashMap();
        header.put("Host", "rmb.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/brac-ia/accountBalance/pages/transactionDetail/transaction.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("acconutFlag","111000");
        params.put("channelCode","C0012");
        params.put("qryType","110");
        var debitBodyInfo = post(urls.Debit_body_url, params, header);
        storeDataToFile(context,debitBodyInfo, "debit_bodyinfo.txt");
        var debitBodyList = JSON.parseObject(debitBodyInfo);
        //判断是否为空
        if(debitBodyInfo.isEmpty() ||  debitBodyList.get("data") == null || debitBodyList.get("data").get("bankCardList").size() == 0){
            return "";
        }
        //解析json串，取出卡片标志
        var bankCardList = debitBodyList.get("data").get("bankCardList").get(0).toString();
        var bank_CardSign = JSON.parseObject(bankCardList).get("bankCardSign").toString();
        return bank_CardSign;
    } catch (e) {
        logger.error("taskKey={} 获取请求体抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 保存未出帐单
 * @param data
 * @return
 * @throws Exception
 */
function saveUnDoneBills(data){
    // TODO Auto-generated method stub
    try{
        var billAllData = new BillAllData();
        var expenseList = billAllData.getShoppingSheets();
        var header = new HashMap();
        header.put("Host", "capp.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/paces-ccms-core/creditcard/billDetail/billDetail.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("accountNo",commMap.get("accountNo"));
        params.put("accountNoIndex",commMap.get("accountNoIndex"));
        params.put("org","242");
        params.put("page","1");
        params.put("queryMonth",month);
        params.put("thirdChannel","");
        params.put("deviceFingerPrint","eyJzZGt2ZXJzaW9uIjoiMS4zLjAiLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDUuMDsgU00tRzkwMFAgQnVpbGQvTFJYMjFUKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNjAuMC4zMTEyLjExMyBNb2JpbGUgU2FmYXJpLzUzNy4zNiIsImxhbmd1YWdlIjoiemgtQ04iLCJsYW5ndWFnZXMiOiJ6aCx6aC1DTiIsImNvbG9yX2RlcHRoIjoyNCwicmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJhdmFpbGFibGVfcmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJ0aW1lem9uZV9vZmZzZXQiOi00ODAsInNlc3Npb25fc3RvcmFnZSI6MSwibG9jYWxfc3RvcmFnZSI6MSwiaW5kZXhlZF9kYiI6MSwib3Blbl9kYXRhYmFzZSI6MSwiY3B1X2NsYXNzIjoidW5rbm93biIsIm5hdmlnYXRvcl9wbGF0Zm9ybSI6IldpbjMyIiwiZG9fbm90X3RyYWNrIjoidW5rbm93biIsImNhbnZhc193aW5kaW5nIjoieWVzIiwiY2FudmFzX2ZwIjoiYjM1NWVkNWMyZjFmMjdjODUxYzc0N2QyMmJmZDY1MDc0Iiwid2ViZ2wiOiIzOGI2MjZlZjYxNjk1NjE5MDJlMGVhMWFhYjJiNDEwNyIsInRvdWNoX3N1cHBvcnQiOiIxLHRydWUsdHJ1ZSIsImNvbXBhdE1vZGUiOiJDU1MxQ29tcGF0IiwiZGV2aWNlUGl4ZWxSYXRpbyI6MywibmF2aWdhdG9yX3ZlbmRvclN1YiI6IiIsIm5hdmlnYXRvcl9wcm9kdWN0U3ViIjoiMjAwMzAxMDciLCJuYXZpZ2F0b3JfdmVuZG9yIjoiR29vZ2xlIEluYy4iLCJuYXZpZ2F0b3JfbWF4VG91Y2hQb2ludHMiOjEsIm5hdmlnYXRvcl9oYXJkd2FyZUNvbmN1cnJlbmN5Ijo0LCJuYXZpZ2F0b3JfY29va2llRW5hYmxlZCI6dHJ1ZSwibmF2aWdhdG9yX2FwcENvZGVOYW1lIjoiTW96aWxsYSIsIm5hdmlnYXRvcl9hcHBOYW1lIjoiTmV0c2NhcGUiLCJuYXZpZ2F0b3JfYXBwVmVyc2lvbiI6IjUuMCAoTGludXg7IEFuZHJvaWQgNS4wOyBTTS1HOTAwUCBCdWlsZC9MUlgyMVQpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS82MC4wLjMxMTIuMTEzIE1vYmlsZSBTYWZhcmkvNTM3LjM2IiwibmF2aWdhdG9yX3Byb2R1Y3QiOiJHZWNrbyIsIm5hdmlnYXRvcl9vbkxpbmUiOnRydWUsInJlZmVyZXIiOiJodHRwczovL2Jhbmstc3RhdGljLnBpbmdhbi5jb20uY24vcGFjZXMtY2Ntcy1jb3JlL2NyZWRpdGNhcmQvYmlsbERldGFpbC9iaWxsRGV0YWlsLmh0bWwiLCJndWlkIjoiYTdjMDM3NmMtODdiYy04YTc3LWViOWQtNWRiNTMxNGQ2YzY4IiwiZGlkIjoiNTg1Zjc0NzI1NDUwZDllZmUzNGIyMDdhZjEyZjRkOTQiLCJvcyI6IlcifQ==");
        params. put("serviceVersion","1.0");
        params.put("osType","1");
        params.put("channel","1");
        params.put("version","1.5.0");
        params.put("nativeDeviceId","");
        params.put("subContracting","");
        var undoneBills = post(urls.Undone_Bills_Url, params, header);
        //var undoneBills = FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\undone_bills.txt"));
        storeDataToFile(context,undoneBills, "undone_bills.txt");
        //防止官网出现异常
        if(undoneBills.contains("发生错误")){
            return data;
        }
        initUsdNull(billAllData);//初始化null值
        var undoneMap = JSON.parseObject(undoneBills);
        //账单编号
        billAllData.setBillId(UUID.randomUUID().toString());
        //账单类型
        billAllData.setBillType("UNDONE");
        //银行
        billAllData.setBankName("平安银行");
        //上期账单金额
        billAllData.setLastBalance(commMap.get("newBalance")==null?null:new BigDecimal(commMap.get("newBalance").toString()));
        //最低还款金额
        billAllData.setMinPayment(null);
        var bigDecimal = new BigDecimal(commMap.get("newBalance")==null?"0":commMap.get("newBalance"));
        //判断是否有未出账单信息
        if(undoneBills.isEmpty()){
            return data;
        }
        var bodyMap = undoneMap.get("body");
        //本期账单金额
        var newbalance = bigDecimal.subtract(new BigDecimal(bodyMap.get("totalRmbPaymentAmt")==null?"0":bodyMap.get("totalRmbPaymentAmt").toString())).add(new BigDecimal(bodyMap.get("rmbConsumptionAmount")==null?"0":bodyMap.get("rmbConsumptionAmount").toString()));
        billAllData.setNewBalance(newbalance);
        //判断信用卡额度是否为空
        if(commMap.get("creditlimit").isEmpty()){
            billAllData.setCreditLimit(null);
        }else{
            billAllData.setCreditLimit(new BigDecimal(commMap.get("creditlimit")));
        }
        //本期新增款额
        billAllData.setNewCharges(new BigDecimal(bodyMap.get("rmbConsumptionAmount")==null?"0":bodyMap.get("rmbConsumptionAmount").toString()));
        //账单日
        var billTime = commMap.get("billDate");
        var limitMes = getLimitMes(commMap.get("lastMonth"));
        //账单月份
        billAllData.setBillMonth(new StringBuffer().append(limitMes.substring(0, limitMes.length()-2)).append("-").append((limitMes.substring(limitMes.length()-2))).toString());
        //判断账单日是否为空
        if(billTime==null || billTime.isEmpty()){
            billAllData.setBillDate(null);//账单日
            billAllData.setPaymentDueDate(null);
        }else{
            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(new StringBuffer().append(billAllData.getBillMonth()).append("-").append(billTime.substring(billTime.length()-2)).toString()));
            //获取未出帐单的还款日
            var paymentduedate = getPaymentdate(billTime.substring(billTime.length()-2).toString());
            billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(new StringBuffer().append(billAllData.getBillMonth()).append("-").append(paymentduedate).toString()));//还款日
        }
        //获取上期还款金额
        if((undoneMap.get("body")).get("totalRmbPaymentAmt")==null){
            billAllData.setLastPayment(null);
        }else{
            billAllData.setLastPayment(new BigDecimal(new StringBuffer().append("-").append((undoneMap.get("body")).get("totalRmbPaymentAmt").toString()).toString()));
        }
        var shoppingList = (undoneMap.get("body")).get("detailList");
        /*var accountList = bodyMap.getJSONArray("accountList");
        if(accountList.size()==0){
            data.getBills().add(billAllData);
            return data;
        }
        else {
            for each (var element in accountList) {
                var accountNoList =element.get("accountNo");
                data.setFullCardNum(accountNoList);//完整卡号
                logger.info("accountNolist{}",accountNoList);
                var  cardNum4 = (accountNoList.substring((accountNoList.length)-4,accountNoList.length));
                data.setCardNum(cardNum4);
                logger.info("cardNum4{}",cardNum4);
                context.put("cardNum4",cardNum4);
            }
        }*/
        //判断消费信息是否为空
        if(shoppingList.size()==0){
            data.getBills().add(billAllData);
            return data;
        }

        //获取消费信息
        getShoppingExpense(shoppingList,expenseList,"undone");
        data.getBills().add(billAllData);
        setShoppingInstallment(billAllData,expenseList)
        return data;
    }catch (e) {
        logger.error("taskKey={} 未出帐单抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 获取未出帐单的还款日
 * @param billdate
 * @return
 */
function getPaymentdate(billdate) {
    // TODO Auto-generated method stub
    var paymentduedate = "";
    if(billdate.equals("03")){
        paymentduedate = "21";
    }else if(billdate.equals("05")){
        paymentduedate = "23";
    }else if(billdate.equals("07")){
        paymentduedate = "25";
    }else if(billdate.equals("10")){
        paymentduedate = "28";
    }else if(billdate.equals("13")){
        paymentduedate = "01";
    }else if(billdate.equals("15")){
        paymentduedate = "03";
    }else if(billdate.equals("17")){
        paymentduedate = "05";
    }else if(billdate.equals("20")){
        paymentduedate = "08";
    }else if(billdate.equals("22")){
        paymentduedate = "10";
    }else if(billdate.equals("25")){
        paymentduedate = "13";
    }else{
        paymentduedate = "13";
    }
    return paymentduedate;
}

/**
 * 保存已出帐单
 * @param data
 * @throws Exception
 */
function saveDoneBills(data){
    // TODO Auto-generated method stub
    try {
        var dataList = data.getBills();
        var count = 0;
        month = commMap.get("firstMonth");
        //循环抓取信用卡12个月的账单信息
        for (var i = 1; i <= 12; i++) {
            var open_time = data.getOpenTime();
            var billAllData = new BillAllData();
            var expenseList = billAllData.getShoppingSheets();
            count++;
            var header = new HashMap();
            header.put("Host", "capp.pingan.com.cn");
            header.put("Origin", "https://bank-static.pingan.com.cn");
            header.put("Referer", "https://bank-static.pingan.com.cn/paces-ccms-core/creditcard/billDetail/billDetail.html");
            header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
            var params = new HashMap();
            params.put("accountNo", commMap.get("accountNo"));
            params.put("accountNoIndex", commMap.get("accountNoIndex"));
            params.put("org", "242");
            params.put("page", "1");
            params.put("queryMonth", month);
            params.put("thirdChannel", "");
            params.put("deviceFingerPrint", "eyJzZGt2ZXJzaW9uIjoiMS4zLjAiLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDUuMDsgU00tRzkwMFAgQnVpbGQvTFJYMjFUKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNjAuMC4zMTEyLjExMyBNb2JpbGUgU2FmYXJpLzUzNy4zNiIsImxhbmd1YWdlIjoiemgtQ04iLCJsYW5ndWFnZXMiOiJ6aCx6aC1DTiIsImNvbG9yX2RlcHRoIjoyNCwicmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJhdmFpbGFibGVfcmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJ0aW1lem9uZV9vZmZzZXQiOi00ODAsInNlc3Npb25fc3RvcmFnZSI6MSwibG9jYWxfc3RvcmFnZSI6MSwiaW5kZXhlZF9kYiI6MSwib3Blbl9kYXRhYmFzZSI6MSwiY3B1X2NsYXNzIjoidW5rbm93biIsIm5hdmlnYXRvcl9wbGF0Zm9ybSI6IldpbjMyIiwiZG9fbm90X3RyYWNrIjoidW5rbm93biIsImNhbnZhc193aW5kaW5nIjoieWVzIiwiY2FudmFzX2ZwIjoiYjM1NWVkNWMyZjFmMjdjODUxYzc0N2QyMmJmZDY1MDc0Iiwid2ViZ2wiOiIzOGI2MjZlZjYxNjk1NjE5MDJlMGVhMWFhYjJiNDEwNyIsInRvdWNoX3N1cHBvcnQiOiIxLHRydWUsdHJ1ZSIsImNvbXBhdE1vZGUiOiJDU1MxQ29tcGF0IiwiZGV2aWNlUGl4ZWxSYXRpbyI6MywibmF2aWdhdG9yX3ZlbmRvclN1YiI6IiIsIm5hdmlnYXRvcl9wcm9kdWN0U3ViIjoiMjAwMzAxMDciLCJuYXZpZ2F0b3JfdmVuZG9yIjoiR29vZ2xlIEluYy4iLCJuYXZpZ2F0b3JfbWF4VG91Y2hQb2ludHMiOjEsIm5hdmlnYXRvcl9oYXJkd2FyZUNvbmN1cnJlbmN5Ijo0LCJuYXZpZ2F0b3JfY29va2llRW5hYmxlZCI6dHJ1ZSwibmF2aWdhdG9yX2FwcENvZGVOYW1lIjoiTW96aWxsYSIsIm5hdmlnYXRvcl9hcHBOYW1lIjoiTmV0c2NhcGUiLCJuYXZpZ2F0b3JfYXBwVmVyc2lvbiI6IjUuMCAoTGludXg7IEFuZHJvaWQgNS4wOyBTTS1HOTAwUCBCdWlsZC9MUlgyMVQpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS82MC4wLjMxMTIuMTEzIE1vYmlsZSBTYWZhcmkvNTM3LjM2IiwibmF2aWdhdG9yX3Byb2R1Y3QiOiJHZWNrbyIsIm5hdmlnYXRvcl9vbkxpbmUiOnRydWUsInJlZmVyZXIiOiJodHRwczovL2Jhbmstc3RhdGljLnBpbmdhbi5jb20uY24vcGFjZXMtY2Ntcy1jb3JlL2NyZWRpdGNhcmQvYmlsbERldGFpbC9iaWxsRGV0YWlsLmh0bWwiLCJndWlkIjoiYTdjMDM3NmMtODdiYy04YTc3LWViOWQtNWRiNTMxNGQ2YzY4IiwiZGlkIjoiNTg1Zjc0NzI1NDUwZDllZmUzNGIyMDdhZjEyZjRkOTQiLCJvcyI6IlcifQ==");
            params.put("serviceVersion", "1.0");
            params.put("osType", "1");
            params.put("channel", "1");
            params.put("version", "1.5.0");
            params.put("nativeDeviceId", "");
            params.put("subContracting", "");
            var doneBill = post(urls.Done_Bills_Url, params, header);
            //var doneBill ="发生错误"
            //var doneBill = FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\done_bills9.txt"));
            storeDataToFile(context, doneBill, "done_bills" + count + ".txt");

            //防止因官网问题导致抓取失败
            if (doneBill.contains("发生错误") || doneBill.contains("系统繁忙，请您重试")) {
                //获取下一个月的月份
                month = getLimitMes(month);
                if (count == 12) {
                    commMap.put("lastMonth", month);
                }
                continue;
            }
            initUsdNull(billAllData);//初始化null值
            var fieldMap = JSON.parseObject(doneBill);
            //防止某个月没有消费记录导致抓取失败
            if (fieldMap == null || fieldMap.isEmpty() || fieldMap.get("body").toString().isEmpty()) {
                month = getLimitMes(month);
                if (count == 12) {
                    commMap.put("lastMonth", month);
                }
                continue;
            }
            var bodyMap = JSON.parseObject(fieldMap.get("body").toString());

            if (count == 12) {
                commMap.put("lastMonth", month);
                if (dataList.size() <= 0) {
                    commMap.put("billDate", null);
                } else {
                    commMap.put("billDate", yyyy_MM_dd_FORMAT.format(dataList.get(0).getBillDate()));
                }
            }
            if ((bodyMap.get("detailList")).isEmpty()) {
                month = getLimitMes(month);
                continue;
            }
            //获取下一个月
            month = getLimitMes(month);
            var dollarAmountToPayOffTotal = bodyMap.get("dollarAmountToPayOffTotal");//本期账单金额-美元
            var billDate = bodyMap.get("billDate");
            commMap.put("billDate", billDate);
            billAllData.setBillId(UUID.randomUUID().toString());//信用卡id
            billAllData.setBillType("DONE");//账单类型，未出UNDONE，已出DONE
            billAllData.setBankName("平安银行");//银行名称
            billAllData.setBillMonth(billDate.substring(0, billDate.length() - 3));//账单月份
            var depoitSdf = new SimpleDateFormat("yyyy-MM-dd");
            //判断账单日是否为空
            if (billDate == null || billDate.isEmpty()) {
                billAllData.setBillDate(billDate);//账单日
            } else {
                if (open_time !== "" && null !== open_time) {
                    if (depoitSdf.parse(billDate).before(open_time)) {
                        continue;
                    }
                }
                billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billDate));//账单日
            }

            if(commMap.get("creditlimit").isEmpty()){
                billAllData.setCreditLimit(null);//信用卡额度
            }else{
                billAllData.setCreditLimit(new BigDecimal(commMap.get("creditlimit")));//信用卡额度
            }
            if (bodyMap.get("paymentDate") == null || bodyMap.get("paymentDate").isEmpty()) {
                billAllData.setPaymentDueDate(bodyMap.get("paymentDate"));//还款日
            } else {
                billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(bodyMap.get("paymentDate")));//还款日
            }
            billAllData.setMinPayment(new BigDecimal(bodyMap.get("rmbMinAmountToPayOffTotal")));//最低还款额
            billAllData.setNewBalance(new BigDecimal(bodyMap.get("totalPaymentDue").toString()));//本期账单金额

            if (!(bodyMap.get("dollarMinAmountToPayOffTotal")).contains("0.00")) {
                billAllData.setUsdMinPayment(new BigDecimal(bodyMap.get("dollarMinAmountToPayOffTotal")));//最低还款额-美元
            }
            if (!(bodyMap.get("dollarAmountToPayOffTotal")).contains("0.00")) {
                billAllData.setUsdNewBalance(new BigDecimal(bodyMap.get("dollarAmountToPayOffTotal")));//本期账单金额-美元
            }
            if (commMap.get("newBalance") == null) {
                billAllData.setLastBalance(null);//上期账单金额
            } else {
                billAllData.setLastBalance(new BigDecimal(commMap.get("newBalance")));//上期账单金额
            }
            if (bodyMap.get("prvPmtAmount").toString().equals("0.00")) {
                billAllData.setLastPayment(null);//上期还款金额
            } else {
                billAllData.setLastPayment(new BigDecimal("-" + bodyMap.get("prvPmtAmount").toString()));//上期还款金额
            }
            billAllData.setNewCharges(new BigDecimal(bodyMap.get("totalPaymentDue")));//本期新增款额
            commMap.put("newBalance", bodyMap.get("totalPaymentDue").toString());
            var shoppingList = bodyMap.get("detailList");
            /*var accountList = bodyMap.getJSONArray("accountList");
            for each (var element in accountList) {
                var accountNoList =element.get("accountNo");
                data.setFullCardNum(accountNoList);//完整卡号
                logger.info("accountNolist{}",accountNoList);
                var  cardNum4 = (accountNoList.substring((accountNoList.length)-4,accountNoList.length));
                data.setCardNum(cardNum4);
                logger.info("cardNum4{}",cardNum4);
                context.put("cardNum4",cardNum4);
            }*/
            //获取消费信息
            getShoppingExpense(shoppingList, expenseList, "Done");
            billAllData.setShoppingSheets(expenseList);
            dataList.add(billAllData);
            //获取分期数据
            setShoppingInstallment(billAllData, expenseList);

        }
        return data;
    }catch (e) {
        logger.error("taskKey={} 已出帐单抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 计算分期数据，从账单中筛选获得
 */
function setShoppingInstallment(billAllData,expenseList){
    try{
        if(expenseList==null || expenseList.size()<=0){
            return;
        }
        var freeList = new ArrayList();//手续费
        var periodList = new ArrayList();//期数

        for each(var expense in expenseList) {
            var des = expense.getDescription();//获取描述
            if(des.contains("分期产品") && !des.contains("结清") && !des.contains("撤销") ){
                if(des.contains("手续费")){
                    freeList.add(expense);
                }else{
                    periodList.add(expense);
                }
            }else{
                if((des.contains("消费专用备用金")&&des.contains("期") )|| (des.contains("消费专用备用金") && des.contains("手续费"))){
                    if(des.contains("手续费")){
                        freeList.add(expense);
                    }else{
                        periodList.add(expense);
                    }
                }
            }
        }

        var instList = new ArrayList();
        var countSize = freeList.size()>periodList.size()?periodList.size():freeList.size();
        for (var i = 0; i < countSize; i++) {
            var free = freeList.get(i);
            var period = periodList.get(i);
            var ins = new Installment();
            ins.setInstallmentDesc((period.getDescription()).replace(/\s+/g, ""));//分期描述
            var goodProduct = free.getDescription().replace(/[^0-9]/ig,"");
            logger.info("goodProduct{}",goodProduct);
            logger.info("period.getDescription(){},free.getDescription(){}",period.getDescription(),free.getDescription());
            ins.setHandingfeeDesc((free.getDescription()).replace(/\s+/g, ""));//分期手续费描述
            ins.setBillId(UUID.randomUUID().toString());//分期编号
            ins.setTransDate(free==null ? null:free.getTransDate());//交易时间
            ins.setPostDate(free==null ? null:free.getPostDate());//记账日期
            ins.setShoppingsheetId(UUID.randomUUID().toString());//消费记录
            ins.setInstallmentType("BILL");//分期类型
            ins.setTransferFee(null);//转账手续费
            var list = new ArrayList();
            var r = Pattern.compile("\\d+");
            var m = r.matcher(period==null ? "":period.getDescription());
            logger.info("m的值{}",m);
            while (m.find()) {
                list.add(Integer.parseInt(m.group()))
            }
            if(list.size()==2){

                if(list.get(0)>13){
                    var totalMonth =  (Integer.toString(list.get(0))).replaceAll(goodProduct,"");
                    logger.info("totalMonth的值{}",totalMonth);
                    ins.setTotalMonth(Integer.parseInt(totalMonth));//总分期数
                }else{

                    ins.setTotalMonth(list.get(0));
                }
                ins.setCurrentMonth(list.get(1));//当前分期数
                logger.info("totalMonth的值是{},currentMonth的值是{}",list.get(0),list.get(1));
            }

            ins.setAmountMoney(period.getAmountMoney());//本期金额
            //ins.setAmountMoney(free.getAmountMoney());//本期金额
            ins.setCurrencyType("CNY");//币种
            ins.setHandingFee(free==null ? new BigDecimal("0"):free.getAmountMoney());//本期手续费
            //ins.setHandingFee(free==null ? new BigDecimal("0"):period.getAmountMoney());//本期手续费
            instList.add(ins);
        }
        billAllData.setInstallments(instList);
    } catch (e) {
        logger.error("taskKey={} 分期数据抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 消费信息
 * @param shoppingList
 * @param expenseList
 * @param type
 */
function getShoppingExpense(shoppingList,expenseList,type){
    try{
        var orderIndex = 0;//交易记录排序
        for(var i = 0;i<shoppingList.size();i++){
            var expense = new Expense();
            expense.setId(UUID.randomUUID().toString());//消费记录ID
            expense.setCardNum(context.get("cardNum4"));//卡号末4位
            //如果是未出账单
            if(type.equals("undone")){
                var postdate = (shoppingList.get(i)).get("postDate").toString();
                var trandate = (shoppingList.get(i)).get("effectDate").toString();
                //记账日期
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(new StringBuffer().append(trandate.substring(0,5)).append(postdate.substring(0,postdate.length()-2)).append("-").append(postdate.substring(postdate.length()-2)).toString()));
                //判断消费类型
                expense.setCategory(judgeBillCategory((shoppingList.get(i)).get("transLog")));//消费类型
                expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(new StringBuffer().append((shoppingList.get(i)).get("effectDate").toString()).append(" 00:00:00").toString()));//交易时间
                expense.setCurrencyType(convertCurr((shoppingList.get(i)).get("consumeCurType")));//币种
                expense.setDescription(((shoppingList.get(i)).get("transLog")).replace(/\s+/g, ""));//描述
            }else{
                expense.setPostDate(yyyy_MM_dd_PARSER.parse((shoppingList.get(i)).get("settleDate")));//记账日期
                expense.setCategory(judgeBillCategory((shoppingList.get(i)).get("txnDesc")));//判断消费类型
                if(((shoppingList.get(i)).get("txnDate")).isEmpty() || (shoppingList.get(i)).get("txnDate") == null){
                    expense.setTransDate("");//交易时间
                }else{
                    expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(new StringBuffer().append((shoppingList.get(i)).get("txnDate").toString()).append(" 00:00:00").toString()));//交易时间
                }
                expense.setCurrencyType(convertCurr((shoppingList.get(i)).get("curType")));//币种
                expense.setDescription(((shoppingList.get(i)).get("txnDesc")).replace(/\s+/g, ""));//描述
            }
            expense.setOrderIndex(++orderIndex);//排序
            expense.setAmountMoney(new BigDecimal((shoppingList.get(i)).get("txnAmount")));//消费金额
            expense.setBalance(null);//余额，因为页面没有显示所以给null
            expense.setTransAddr("");//交易地点
            expense.setTransMethod("");//交易方式
            expense.setTransChannel("");//交易通道
            expense.setRemark("");//备注
            expense.setOppositeCardNo("");//对方卡号
            expense.setNameOnOppositeCard("");//对方持卡人
            expense.setOppositeBank("");//对方银行
            expenseList.add(expense);
        }
    } catch (e) {
        logger.error("taskKey={} 消费信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 根据中文币种生成英文币种
 */
function convertCurr(currencyType) {
    if (StringUtils.isNotBlank(currencyType)) {
        if(currencyType.contains("242") || currencyType.contains("RMB")){
            return "CNY";
        }else{//美元方式暂时未知
            return "其他";
        }
    } else {
        return "";
    }
}

/**
 * 根据描述判断账单的消费类型
 */
function judgeBillCategory(description) {
    if(description.length == 0){
        return "";
    }
    if (description.contains("消费")) {
        return "SHOPPING";
    }else if (description.contains("取现")) {
        return "WITHDRAW";
    }else if (description.contains("还款")||description.contains("转入")) {
        return "PAYMENTS";
    }else if (description.contains("逾期利息")||description.contains("利息")) {
        return "INTEREST";
    }else if (description.contains("延滞金") || description.contains("滞纳金") || description.contains("违约金")) {
        return "OVERDUEPAYMENT";
    }else if (description.contains("超额费")) {
        return "OVERDUEFEE";
    }else if (description.contains("分期")) {
        return "INSTALLMENT";
    }else if (description.contains("年费")) {
        return "OTHERFEE";
    }else{
        return "OTHERFEE";
    }
}

/**
 *
 * 获取月份
 * @param month
 * @throws ParseException
 */
function getLimitMes(month){
    try{
        var sdf=new SimpleDateFormat("yyyyMM");
        var date = sdf.parseObject(month);
        var calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        var resultDate = calendar.getTime();
        month=sdf.format(resultDate);
        return month;
    }catch (e) {
        logger.error("taskKey={} 获取月份抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 初始化null值，美元相关
 */
function initUsdNull(billAllData){
    //美元相关
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setInterest(null);
    billAllData.setCashLimit(null);
}

/**
 * 保存基本信息
 * @param data
 * @throws Exception
 */
function clickCreditCard(data){
    try {
        //解析基本信息json串
        var fieldMap = JSON.parseObject(commMap.get("queryBasicHtml"));
        //判断是否为空
        if (commMap.get("queryBasicHtml").isEmpty()) {
            return 0;
        }
        var parse = (JSON.parseObject(fieldMap.get("body").toString())).get("acctList");
        //获取可查询的月份列表
        var monthList = (JSON.parseObject(fieldMap.get("body").toString())).get("monthList");
        //获取完整卡号
        var cardparse = (parse.get(0)).get("cardSet");

        //获取卡号方法
        var cardHeader = new HashMap();
        cardHeader.put("Host", "capp.pingan.com.cn");
        cardHeader.put("Origin", "https://bank-static.pingan.com.cn");
        cardHeader.put("Referer", "https://bank-static.pingan.com.cn/paces-ccms-core/creditcard/billStaging/billStaging.html");
        cardHeader.put("User-Agent", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36");
        var CardParams = new HashMap();
        CardParams.put("serviceVersion","1.0");
        CardParams.put("osType","1");
        CardParams.put("channel","1");
        CardParams.put("version","1.5.0");
        CardParams.put("nativeDeviceId","");
        CardParams.put("device","");
        CardParams.put("subContracting","");
        var fullCardNum = post(urls.Get_Full_Card_Num_URL, CardParams, cardHeader);
        storeDataToFile(context, fullCardNum,"full_card_num.txt");

        var fieldMap = JSON.parseObject(fullCardNum);
        logger.info("输出fileMap{}",fieldMap);
        var bodyMap = JSON.parseObject(fieldMap.get("body").toString());
        logger.info("输出bodyMap{}",bodyMap);
        var full_card_num = bodyMap.get("cardNo");
        logger.info("输出full_card_num{}",full_card_num);





        //var full_card_num = (cardparse.get(0)).get("cardNo");

        data.setCardId(UUID.randomUUID().toString());
        data.setCardType("信用卡");//卡类型
        data.setBankName("平安银行");//银行
        data.setFullCardNum(full_card_num);//完整卡号
        data.setCardNum(full_card_num.substring(full_card_num.length() - 4));//卡号末四位
        context.put("cardNum4",full_card_num.substring(full_card_num.length() - 4));
        data.setOpenBank("平安银行");//开户银行
        data.setCashLimit(null);//预借现金额度
        data.setOpenTime(yyyy_MM_dd_PARSER.parse((cardparse.get(0)).get("dateOpen")));//开户时间
        commMap.put("accountNo", (parse.get(0)).get("accountNo"));
        commMap.put("accountNoIndex", (parse.get(0)).get("accountNoIndex"));
        commMap.put("firstMonth", (JSON.parseObject(monthList.get(monthList.size() - 1).toString())).get("month"));
        //获取持卡人姓名
        var name_oncard = getName();
        data.setNameOnCard(name_oncard);//持卡人姓名
        //获取信用卡额度
        getQuotas(data);
    }catch (e) {
        logger.error("taskKey={} 保存基本信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}


/**
 * 获取持卡人姓名
 */
function getName(){
    try{
        var userheader = new HashMap();
        userheader.put("Host", "rmb.pingan.com.cn");
        userheader.put("Origin", "https://b.pingan.com.cn");
        userheader.put("Referer", "https://b.pingan.com.cn/platform/mine/module/mine.html");
        userheader.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var usrparams = new HashMap();
        usrparams.put("channelId","BANK-MOBILESITE");
        var getUsername = post(urls.Get_User_URL, usrparams, userheader);
        storeDataToFile(context, getUsername,"username.txt");
        //解析json串，获取持卡人姓名
        var username = (JSON.parseObject(getUsername)).get("clientName").toString();
        return username;
    } catch (e) {
        logger.error("taskKey={} 获取持卡人姓名抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 获取信用卡额度
 * @param data
 * @throws Exception
 */
function getQuotas(data){
    // TODO Auto-generated method stub
    try {
        var header = new HashMap();
        header.put("Host", "capp.pingan.com.cn");
        header.put("Origin", "https://b.pingan.com.cn");
        header.put("Referer", "https://b.pingan.com.cn/paces-ccms-core/mobilesite/myAmountMZ/myAmountMZ.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("serviceVersion", "1.0");
        params.put("osType", "1");
        params.put("channel", "1");
        params.put("version", "1.5.0");
        params.put("nativeDeviceId", "");
        params.put("subContracting", "");
        var quotasMes = post(urls.Get_Quotas_URL, params, header);
        storeDataToFile(context, quotasMes, "credit_quotas.txt");
        quotasMes = "{'body':'','code':'601','message':'操作失败,请您重试'}";
        //重试防止出现系统繁忙
        for (var i = 0; i <= 3; i++) {
            if (quotasMes.contains("系统繁忙，请您重试") || quotasMes.contains("操作失败,请您重试")) {
                var quotasMes = post(urls.Get_Quotas_URL, params, header);
                storeDataToFile(context, quotasMes, "credit_quotas" + i + ".txt");
            } else {
                break;
            }
        }
        if(quotasMes.contains("系统繁忙，请您重试") || quotasMes.contains("操作失败,请您重试")){
            data.setCreditLimit(null);//信用卡额度
            data.setBalance(null);//可用额度
            data.setCashBalance(null);//可取现额度
            commMap.put("balance", "");
            commMap.put("creditlimit", "");
        }else{
            //解析json串获取字段
            var parse = (JSON.parseObject((JSON.parseObject(quotasMes)).get("body").toString())).get("accountList");
            var cardMap = JSON.parseObject(parse.get(0).toString());
            data.setCreditLimit(new BigDecimal(cardMap.get("limit").toString()));//信用卡额度
            data.setBalance(new BigDecimal(cardMap.get("availableLimit").toString()));//可用额度
            data.setCashBalance(new BigDecimal(cardMap.get("cashLimit").toString()));//可取现额度
            commMap.put("balance", data.getBalance().toString());
            commMap.put("creditlimit", data.getCreditLimit().toString());
        }

    }catch (e) {
        logger.error("taskKey={} 信用卡额度抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}

/**
 * 判断是否有卡片信息
 * @throws Exception
 */
function checkIsCard(){
    // TODO Auto-generated method stub
    var queryBasicHtml = "";
    for(var i = 0;i<=3;i++){
        var header = new HashMap();
        header.put("Host", "capp.pingan.com.cn");
        header.put("Origin", "https://bank-static.pingan.com.cn");
        header.put("Referer", "https://bank-static.pingan.com.cn/paces-ccms-core/creditcard/billDetail/billDetail.html");
        header.put("User-Agent", "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        var params = new HashMap();
        params.put("deviceFingerPrint","eyJzZGt2ZXJzaW9uIjoiMS4zLjAiLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDUuMDsgU00tRzkwMFAgQnVpbGQvTFJYMjFUKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNjAuMC4zMTEyLjExMyBNb2JpbGUgU2FmYXJpLzUzNy4zNiIsImxhbmd1YWdlIjoiemgtQ04iLCJsYW5ndWFnZXMiOiJ6aCx6aC1DTiIsImNvbG9yX2RlcHRoIjoyNCwicmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJhdmFpbGFibGVfcmVzb2x1dGlvbiI6IjY0MCwzNjAiLCJ0aW1lem9uZV9vZmZzZXQiOi00ODAsInNlc3Npb25fc3RvcmFnZSI6MSwibG9jYWxfc3RvcmFnZSI6MSwiaW5kZXhlZF9kYiI6MSwib3Blbl9kYXRhYmFzZSI6MSwiY3B1X2NsYXNzIjoidW5rbm93biIsIm5hdmlnYXRvcl9wbGF0Zm9ybSI6IldpbjMyIiwiZG9fbm90X3RyYWNrIjoidW5rbm93biIsImNhbnZhc193aW5kaW5nIjoieWVzIiwiY2FudmFzX2ZwIjoiYjM1NWVkNWMyZjFmMjdjODUxYzc0N2QyMmJmZDY1MDc0Iiwid2ViZ2wiOiIzOGI2MjZlZjYxNjk1NjE5MDJlMGVhMWFhYjJiNDEwNyIsInRvdWNoX3N1cHBvcnQiOiIxLHRydWUsdHJ1ZSIsImNvbXBhdE1vZGUiOiJDU1MxQ29tcGF0IiwiZGV2aWNlUGl4ZWxSYXRpbyI6MywibmF2aWdhdG9yX3ZlbmRvclN1YiI6IiIsIm5hdmlnYXRvcl9wcm9kdWN0U3ViIjoiMjAwMzAxMDciLCJuYXZpZ2F0b3JfdmVuZG9yIjoiR29vZ2xlIEluYy4iLCJuYXZpZ2F0b3JfbWF4VG91Y2hQb2ludHMiOjEsIm5hdmlnYXRvcl9oYXJkd2FyZUNvbmN1cnJlbmN5Ijo0LCJuYXZpZ2F0b3JfY29va2llRW5hYmxlZCI6dHJ1ZSwibmF2aWdhdG9yX2FwcENvZGVOYW1lIjoiTW96aWxsYSIsIm5hdmlnYXRvcl9hcHBOYW1lIjoiTmV0c2NhcGUiLCJuYXZpZ2F0b3JfYXBwVmVyc2lvbiI6IjUuMCAoTGludXg7IEFuZHJvaWQgNS4wOyBTTS1HOTAwUCBCdWlsZC9MUlgyMVQpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS82MC4wLjMxMTIuMTEzIE1vYmlsZSBTYWZhcmkvNTM3LjM2IiwibmF2aWdhdG9yX3Byb2R1Y3QiOiJHZWNrbyIsIm5hdmlnYXRvcl9vbkxpbmUiOnRydWUsInJlZmVyZXIiOiJodHRwczovL2Jhbmstc3RhdGljLnBpbmdhbi5jb20uY24vcGFjZXMtY2Ntcy1jb3JlL2NyZWRpdGNhcmQvYmlsbERldGFpbC9iaWxsRGV0YWlsLmh0bWwiLCJndWlkIjoiYTdjMDM3NmMtODdiYy04YTc3LWViOWQtNWRiNTMxNGQ2YzY4IiwiZGlkIjoiNTg1Zjc0NzI1NDUwZDllZmUzNGIyMDdhZjEyZjRkOTQiLCJvcyI6IlcifQ==");
        params.put("serviceVersion","1.0");
        params.put("osType","1");
        params.put("channel","1");
        params.put("subContracting","");
        queryBasicHtml = post(urls.Query_Basic, params, header);
        storeDataToFile(context, queryBasicHtml, "basic_mes.txt");
        //如果页面中包含错误信息四个字，再次循环，一共请求三次
        if(!queryBasicHtml.contains("错误信息")){
            break;
        }
    }
    if(strIsJSON(queryBasicHtml)){
        var jsonResult = JSON.parseObject(queryBasicHtml);
        if("0".equals(jsonResult.getString("code")) && "操作成功".equals(jsonResult.getString("message"))){
            commMap.put("queryBasicHtml", queryBasicHtml);
            return "true";
        }else{
            return jsonResult.getString("message")==null ? jsonResult.getString("responseMsg") : jsonResult.getString("message");
        }

    }else{
        return "未获取到卡片信息";
    }
}
/**
 * 判断字符串是否是json格式
 * @param str
 * @returns {boolean}
 */
function strIsJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parseObject(str);
            if(typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }

        } catch(e) {
            print('error：'+str+'!!!'+e);
            return false;
        }
    }
    print.log('It is not a string!')
}

var luaFuncs = {
    open: function (url) {
        var map = new HashMap();
        map.put("method","open");
        map.put("url",url);
        return sendAndReceive(map);
    },
    submitlogin: function (password,publicKey) {
        var map = new HashMap();
        map.put("method","submitlogin");
        map.put("password",password);
        map.put("publicKey",publicKey);
        return sendAndReceive(map);
    }

}
